package com.example.gw_back_end.service.provider;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.gw_back_end.domain.PageParam;
import com.example.gw_back_end.domain.PageResult;
import com.example.gw_back_end.domain.entities.MinioBucket;
import com.example.gw_back_end.mapper.MinioBucketMapper;
import com.example.gw_back_end.utils.GenerateRandomKeyUtil;
import com.example.gw_back_end.utils.MinioUtil;
import com.example.gw_back_end.utils.ThreadLocalUtil;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.MinioProperties;
import io.minio.admin.MinioAdminClient;
import io.minio.admin.UserInfo;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service
public class MinIOService {

    private final MinioUtil minioUtil;
    private final MinioBucketMapper minioBucketMapper;
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioAdminClient minioAdminClient;

    public MinIOService(MinioUtil minioUtil, MinioBucketMapper minioBucketMapper) {
        this.minioUtil = minioUtil;
        this.minioBucketMapper = minioBucketMapper;
    }

    @Value("${minio.tempBucketName}")
    private String tempBucketName;

//     @Scheduled(fixedRate = 10000) // 这个是固定时间间隔 ms 为单位
//    @Scheduled(cron = "0 0 0 * * ?")
//    public void index() {
//        minioUtil.clearBucket(tempBucketName);
//    }

    // 为开发商创建Minio存储桶
    public String createMinioBucket() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer accountType = (Integer) claims.get("accountType");
        Integer status = (Integer) claims.get("status");
        if ( accountType.equals(1) || accountType.equals(2) || accountType.equals(3) || accountType.equals(4) && status.equals(0)){

            String accessKey = GenerateRandomKeyUtil.generateRandomKey(15);
            String secretKey = GenerateRandomKeyUtil.generateRandomKey(24);

            String minioBucketName = generateValidBucketName();

            minioUtil.createBucket(minioBucketName);

            MinioBucket minioBucket = new MinioBucket();
            minioBucket.setUserId((Integer) claims.get("id"));
            minioBucket.setMinioBucketName(minioBucketName);
            minioBucket.setCreateTime(LocalDateTime.now());
            if (minioBucketMapper.insert(minioBucket) > 0) {
                return minioBucketName;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    // 根据id删除Minio存储桶
    public boolean deleteBucket(Integer minioBucketId) {
        String minioBucketName = minioBucketMapper.selectById(minioBucketId).getMinioBucketName();
        if(minioBucketMapper.deleteById(minioBucketId) > 0){
            try {
                minioUtil.deleteBucket(minioBucketName);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    // 根据id获取Minio存储桶
    public MinioBucket getMinioBucket(Integer minioBucketId) {
        return minioBucketMapper.selectById(minioBucketId);
    }

    // 获取Minio存储桶列表
    public PageResult<MinioBucket> getMinioBucketList(PageParam pageParam) {
        Page<MinioBucket> minioBucketPage = minioBucketMapper.selectPage(new Page<>(pageParam.getPage(),pageParam.getSize()),null);
        return PageResult.setPageResult(minioBucketPage);
    }

    public String generateValidBucketName() {
        return UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
    }

//    public void createUserWithPolicy(String accessKey, String secretKey, String policyName) throws Exception {
//        // 检查策略是否存在（可选）
//        // 如果策略需要动态创建，需先调用addPolicy方法
//
//        // 创建用户
//        minioAdminClient.addUser(accessKey, UserInfo.Status.ENABLED,secretKey, policyName, null);
//    }
//
//    // 可选：创建自定义策略
//    public void createCustomPolicy(String policyName, String policyJson) throws Exception {
//        minioAdminClient.setPolicy(policyName,policyJson);
//    }

//    public void test () {
//        minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
//                .method(Method.POST)
//                .bucket()
//                .expiry(300)
//                )
//    }

    // 创建用户
    public String createUserWithPolicy(String accessKey,String secretKey,String policyName) throws Exception {
        minioAdminClient.addUser(accessKey,UserInfo.Status.ENABLED,secretKey,policyName,null);
        return null;
    }



}
